<?php

namespace App\Http\Middleware;
use App\Consts\ExceptionCodeConst;
use App\Consts\GlobalConst;
use Closure;

use Illuminate\Http\Request;

class PagesAuthenticate
{

    /**
     * Handle an incoming request.
     * 页面参数签名认证
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 本地和开发环境跳过参数验证
        if (isLocal() || isDev()) {
            return $next($request);
        }

        // 获取参数
        $bodyForm = $request->all();
        try {
            // 验证 keys
            $keys = !empty($bodyForm['keys']) ? $bodyForm['keys'] : '';
            if (empty($bodyForm['keys'])) {
                //throw new \Exception(lang('Missing Params'), ExceptionCodeConst::MISSING_PARAMETER);
                throw new \Exception(lang('Page expired'), ExceptionCodeConst::ROUTE_PAGE_EXPIRED);
            }
            if (!$this->matchTime($keys)) {
                throw new \Exception(lang('Page expired'), ExceptionCodeConst::ROUTE_PAGE_EXPIRED);
            }
        } catch (\Exception $e) {
            return appThrow($e);
        }

        return $next($request);
    }

    /**
     * 匹配时间是否过期
     * @param $keys
     * @return bool
     */
    public function matchTime($keys)
    {
        $time = time() - GlobalConst::SIGN_EXPIRED_TIME_PAGES;
        for ($i = 1; $i <= GlobalConst::SIGN_EXPIRED_TIME_PAGES; $i++) {
            $rows = 'timestamp=' . ($time + $i) . '&key=' . GlobalConst::SECRET_MSG_CENTER_PAGES;
            $check = md5($rows);
            if ($check === $keys) {
                return true;
            }
        }
        return false;
    }

}